import './index_PC.scss';
import React, { useEffect, useState, useRef } from "react";
import { user_settings, user_config_set } from '@/utils/mixin.ts'
import { Button, List, message} from 'antd';
import { ArrowLeftOutlined, FallOutlined } from '@ant-design/icons';

const General = () => {
    const [settingsList, setSettingsList] = useState([]);
    const [editState, setEditState] = useState(false);
    const [editValue, setEditValue] = useState('');

    useEffect(() => {
        getUserSettings();
    }, []);  // 空数组表示只在组件挂载时执行
    const getUserSettings = () => {
        user_settings({
            email: localStorage.getItem('email')

        }).then(res => {
            if (res) {
                setSettingsList(res.data);
            }
        });
    }
    const edit = async() => {
        editState ? setEditState(false) : setEditState(true);
        setEditValue(settingsList.length && settingsList[0].config_value *100)
        if (editState && editValue!=='') {
            await user_config_set({
                email: localStorage.getItem('email'),
                config_key: settingsList[0].config_key,
                config_value: editValue / 100
            }).then(res => {
                if (res) {
                    getUserSettings();
                } else {
                    message.error(res.msg);
                }
            });
        }
    }

    return (
        <div className="general">
            <div className="header_general">
                <Button type="text" className="goBackBtn" onClick={() => window.history.go(-1)} icon={<ArrowLeftOutlined />}></Button>
                <p className="title">General</p>
            </div>
            <div className="content_general">
                <List
                    className="demo-loadmore-list"
                    itemLayout="horizontal"
                    dataSource={settingsList}
                    renderItem={(item, ind) => (
                        !ind && <List.Item
                            actions={[<span className="editBtn" onClick={() => edit()}>edit</span>]}
                        >
                            <List.Item.Meta
                                avatar={<FallOutlined />}
                                title={<span>{item.config_key}</span>}
                            />
                            {editState ?
                            <div><input className="editInput" value={editValue} onChange={(e) => { setEditValue(e.target.value) }}/> % </div>:
                            <div className='config_value'>{item.config_value * 100} %</div>}
                        </List.Item>
                    )}
                />
            </div>
        </div>
    )

}

export default General;